package org.mspring.mlog.web.task.comment;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.mspring.mlog.entity.Comment;
import org.mspring.mlog.service.PostService;
import org.mspring.mlog.utils.PostUrlUtils;
import org.mspring.platform.config.ConfigService;
import org.mspring.platform.mail.MailService;
import org.mspring.platform.task.AbstractTask;
import org.mspring.platform.utils.FreemarkerUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import freemarker.template.Configuration;

/**
 *
 * @since 2014-04-10 15:12:00
 * @author Gao Youbo
 */
@Component
public class CommentReplyNoticeTask extends AbstractTask {

    private static final Logger log = LoggerFactory.getLogger(CommentReplyNoticeTask.class);

    private static final String FTL = "/mail/comment_reply_notice.ftl";

    @Autowired
    private ConfigService configService;
    @Autowired
    private MailService mailService;
    @Autowired
    private PostService postService;
    @Autowired
    private Configuration configuration;

    @Override
    protected void doTask(Map<Object, Object> paramMap) throws Exception {
        Comment comment = (Comment) paramMap.get("comment");
        if (comment == null || comment.getParent() == null || StringUtils.isBlank(comment.getParent().getEmail())) {
            return;
        }
        String commentUrl = PostUrlUtils.getPostAbsUrl(comment.getPost().getId());

        Map<Object, Object> model = new HashMap<Object, Object>();
        model.put("commentUrl", commentUrl);
        model.put("comment", comment);
        model.put("post", comment.getPost());

        String to = comment.getParent().getEmail();
        String personal = comment.getParent().getAuthor();
        String subject = configService.getConfig("sitename") + " - 评论回复通知";

        if (StringUtils.isBlank(to)) {
            log.warn("发送回复通知失败，邮箱为空, comment={}", comment.getId());
            return;
        }

        String content = FreemarkerUtils.render(configuration, FTL, model);
        mailService.sendMail(to, personal, subject, content);
    }

}
